package zb.WX.util;

import com.google.gson.Gson;
import zb.WX.bean.jsSdk.JsApiTicket;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

public class JsApiTicketSaveUtil {
    /*
     * 将获取到的jsapi_ticket保存到本地。按上面的规则获取
     * 此方法依赖于refershJSApiTicket()方法
     */
    public static String getLocationJsApiTicket() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        String result = null;
        Gson gson = new Gson();
        File file = new File(PropertiesUtil.getPropValue("jsapiTicketFile"));
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (file.length() == 0) {//如果文件中没有内容则发送get请求获取jsapiTicket并将其存入文件
            result = refershJSApiTicket();
            try {
                fos = new FileOutputStream(file, false);//不追加内容，直接覆盖
                JsApiTicket jt = new JsApiTicket();
                jt.setTicket(result);
                jt.setExpires_in(new Date().getTime());
                String accessTokenJson = gson.toJson(jt);
                fos.write(accessTokenJson.getBytes());//将获取到的jsapiTicket存储到文件
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("第一次获取并创建文件，获取到了jsapi_ticket");
            return result;
        } else {//获取文件中的jsapiTicket
            byte[] b = new byte[1024];
            try {
                fis = new FileInputStream(file);
                int len = 0;
                result = "";
                while ((len = fis.read(b)) != -1) {
                    result += new String(b, 0, len);
                }
                JsApiTicket jsApiTicket = gson.fromJson(result, new JsApiTicket().getClass());
                if (jsApiTicket.getExpires_in() != null) {
                    long overtime = System.currentTimeMillis() - jsApiTicket.getExpires_in();
                    if (GlobalVar.EXPIRES_IN * 1000 < overtime) {//如果超过2小时，发送请求获取jsapiTicket
                        result = refershJSApiTicket();
                        fos = new FileOutputStream(file, false);//不追加内容，直接覆盖
                        JsApiTicket jt = new JsApiTicket();
                        jt.setTicket(result);//重新获取jsapiTicket
                        jt.setExpires_in(new Date().getTime());
                        String jsApiTicketJson = gson.toJson(jt);
                        fos.write(jsApiTicketJson.getBytes());//将获取到的jsapiTicket存储到文件
                        fos.close();
                        System.out.println("超时获取到了jsapi_ticket");
                    } else {//没有超过两个小时直接文件中获取jsapi_ticket
                        System.out.println("从文件中获取到了jsapi_ticket");
                        return jsApiTicket.getTicket();
                    }
                } else {
                    return null;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    }


    /**
     * 请求微信服务端获取到的jsapi_ticket格式如下:
     * {
     * "errcode":0,
     * "errmsg":"ok",
     * "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
     * "expires_in":7200
     * }
     * 是一个json类型的字符串，我们用Gson（第三方jar包）将其转化为JsApiTicket实体对象，然后获取ticket
     *
     * @return
     */
    public static String refershJSApiTicket() {
        //需要使用基础的access_token获取jsapi_ticket
        String accessTokenUrl = GlobalVar.JSAPI_TICKET.replace("ACCESS_TOKEN", AccessTokenSaveUtil.getLocationAccesstonken());
        String result = null;
        InputStreamReader isr = null;
        try {
            URL url = new URL(accessTokenUrl);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            isr = new InputStreamReader(httpsConn.getInputStream());
            char[] c = new char[1024];
            int len;
            result = "";
            while ((len = isr.read(c)) != -1) {
                result += new String(c, 0, len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        Gson gson = new Gson();
        JsApiTicket jsApiTicket = gson.fromJson(result, new JsApiTicket().getClass());//将获取到的
        if (jsApiTicket != null) {
            return jsApiTicket.getTicket();
        } else {
            System.out.println("及时获取jsapi_ticket失败");
            return null;
        }
    }
}
